package com.example.demo.common;

import com.example.demo.game.*;
import com.example.demo.model.Userinfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;

/**
 * 人机对战的websocket
 */
@Component
public class TextMachine extends TextWebSocketHandler {

    private ObjectMapper objectMapper=new ObjectMapper();

    @Autowired
    private GetUserLoginMatch getUserLogin;

    @Autowired
    private RoomManager roomManager;
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        Userinfo userinfo = (Userinfo) session.getAttributes().get(AppValues.USER_KEY);
        RespReadyGame respReadyGame =new RespReadyGame();
        if(userinfo==null) {//此用户未登录
            System.out.println("未登录");
            respReadyGame.setOk(false);
            respReadyGame.setReason("未登录");
            respReadyGame.setMessage("noReady");//未就绪
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(respReadyGame)));
            return;
        }
        WebSocketSession socketSession =getUserLogin.getFromGameHall(userinfo.getUserid());
        if(socketSession!=null) {
            RespMatch respMatch =new RespMatch();
            respMatch.setOk(true);
            respMatch.setMessage("noshuang");
            respMatch.setReason("禁止多开");
            //将已经登录的信息返回去并关闭连接
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(respMatch)));
            //关闭连接后会调用关闭连接的方法
            socketSession.close();
        }
        getUserLogin.enterGameGame(userinfo.getUserid(),session);//判断完后加入对战状态
        MachineRoom room =new MachineRoom();//新建的房间
        room.setUserinfo1(userinfo);//设置一个人
        room.setWhitestatr(userinfo.getUserid());//设置先手玩家为真人
        roomManager.addMachineRoom(room,userinfo);
        noticeGameReady(room,room.getUserinfo1().getUserid());//返回准备就绪响应
    }
    /**
     * 向客户端返回玩家准备就绪的响应
     * @param room
     * @param userid1
     * @throws IOException
     */
    private void noticeGameReady(MachineRoom room, Integer userid1) throws IOException {
        RespReadyGame respReadyGame =new RespReadyGame();
        respReadyGame.setMessage("gameReady");//准备就绪的约定
        respReadyGame.setOk(true);
        respReadyGame.setRoomid(room.getRoomId());
        respReadyGame.setUserid1(userid1);
        respReadyGame.setWhiteUser(room.getWhitestatr());
        WebSocketSession session=getUserLogin.getFromGameGame(userid1);
        session.sendMessage(new TextMessage(objectMapper.writeValueAsString(respReadyGame)));
    }
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        Userinfo userinfo = (Userinfo) session.getAttributes().get(AppValues.USER_KEY);
        if(userinfo==null) {
            System.out.println("未登录");
        }
        MachineRoom room=roomManager.getMaRoomByUserId(userinfo.getUserid());
        room.putchess(message.getPayload());
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("连接错误");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("连接关闭");
    }
}
